package com.soledroid;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.github.droidfu.widgets.WebImageView;
import com.soledroid.Model.Dish;
import com.soledroid.Model.Stall;
import com.soledroid.item.FoodItem;
import com.soledroid.item.Item;
import com.soledroid.item.PlaceItem;
import com.soledroid.item.SectionItem;

public class SearchActivity extends Activity {
	private ListView listView;
	ArrayList<Item> items = new ArrayList<Item>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.search_layout);

	    // Get the intent, verify the action and get the query
	    handleIntent(getIntent());
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
	    setIntent(intent);
	    handleIntent(intent);
	}
	
	private void handleIntent(Intent intent){
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
		    doMySearch(query);
		}
	}

	private void doMySearch(String query) {
		// TODO Auto-generated method stub
		
		try {
			URI uri = new URI(
				    "http", 
				    "soledroid.huytoan.com", 
				    "/search/" + query,
				    null);
			URL url = uri.toURL();
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONObject json = new JSONObject(line);
				
				items.add(new SectionItem("Dishes"));
				JSONArray dishes = json.getJSONArray("dishes");
				
				for (int i = 0; i < dishes.length(); i++) {
					JSONObject jo = (JSONObject) dishes.get(i);

					Dish dish = new Dish(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
							jo.getString("description"), jo.getString("price"), jo.getInt("stall_id"),
							jo.getInt("on_promotion") == 1, jo.getDouble("rating"));
					items.add(new FoodItem(dish.getId(), dish.getName(), dish.getDescription(), dish.getImage(), dish.getPrice(), (int)dish.getRating()));
				}
				
				items.add(new SectionItem("Stalls"));
				JSONArray stalls = json.getJSONArray("stalls");

				for (int i = 0; i < stalls.length(); i++) {
					JSONObject jo = (JSONObject) stalls.get(i);

					Stall stall = new Stall(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
                    		jo.getString("description"), jo.getInt("canteen_id"));
					items.add(new PlaceItem(stall.getId(), stall.getName(), stall.getDescription(), stall.getImage()));
				}
			}
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        
        EntryAdapter adapter = new EntryAdapter(this, items);
        listView = (ListView) findViewById(R.id.search_result_list);
        listView.setAdapter(adapter);
        
        listView.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {     
        		
        		switch(items.get(position).getType()) {
        		case SECTION:
        			break;
        		case FOOD:
        			Intent i = new Intent(getApplicationContext(),
    						DishActivity.class);

    				FoodItem foodItem = (FoodItem) items.get(position);
    				i.putExtra("name", foodItem.name);
    				i.putExtra("id", foodItem.id);

    				SearchActivity.this.startActivity(i);
        			break;
        		case PLACE:
        			Intent ii = new Intent(getApplicationContext(), StallActivity.class); 

        			PlaceItem placeItem = (PlaceItem) items.get(position);
    				ii.putExtra("name", placeItem.name);
    				ii.putExtra("id", placeItem.id);

    				SearchActivity.this.startActivity(ii);
    				break;
        		}
        			
        	}
        });
	}
	
	public class EntryAdapter extends ArrayAdapter<Item> {
		private ArrayList<Item> items;
		private LayoutInflater vi;

		public EntryAdapter(Context context, ArrayList<Item> items) {
			super(context, 0, items);
			this.items = items;
			vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;

			final Item i = (Item) items.get(position);
			if (i != null) {
				switch(i.getType()) {
					case SECTION:
						SectionItem si = (SectionItem)i;
						v = vi.inflate(R.layout.search_section, null);
	
						v.setOnClickListener(null);
						v.setOnLongClickListener(null);
						v.setLongClickable(false);
	
						final TextView sectionView = (TextView) v.findViewById(R.id.search_section_text);
						sectionView.setText(si.getTitle());
						break;
					
					case FOOD:
						FoodItem fi = (FoodItem)i;
						v = vi.inflate(R.layout.search_result_food_entry, null);
						final TextView foodNameView = (TextView)v.findViewById(R.id.search_food_name);
						final TextView foodWhereView = (TextView)v.findViewById(R.id.search_food_where);
						final WebImageView foodImageView = (WebImageView)v.findViewById(R.id.search_food_img);
						final RatingBar foodRatingBar = (RatingBar)v.findViewById(R.id.search_food_rating);

						if(foodNameView != null)
							foodNameView.setText(fi.name);
						if(foodWhereView != null){
							if(fi.description.equals("null")){
								foodWhereView.setText("$" + fi.price + " - " + fi.description);
							} else {
								foodWhereView.setText("$" + fi.price);
							}
						}
						if(foodImageView != null){
							try {
								foodImageView.setImageUrl(fi.image);
								foodImageView.loadImage();
					        } catch (Exception e) {
					            e.printStackTrace();
					        }
						}
						if(foodRatingBar != null){
							foodRatingBar.setRating(fi.rating);
						}
						
						break;
					
					case PLACE:
						PlaceItem pi = (PlaceItem)i;
						v = vi.inflate(R.layout.search_result_food_entry, null);
						final TextView placeNameView = (TextView)v.findViewById(R.id.search_food_name);
						final TextView placeAddressView = (TextView)v.findViewById(R.id.search_food_where);
						final WebImageView placeImageView = (WebImageView)v.findViewById(R.id.search_food_img);
						final RatingBar placeRatingBar = (RatingBar)v.findViewById(R.id.search_food_rating);

						if(placeNameView != null)
							placeNameView.setText(pi.name);
						if(placeAddressView != null)
							placeAddressView.setText(pi.description);	
						if(placeImageView != null){
							try {
								placeImageView.setImageUrl(pi.image);
								placeImageView.loadImage();
					        } catch (Exception e) {
					            e.printStackTrace();
					        }
						}
						if(placeRatingBar != null){
							placeRatingBar.setVisibility(View.INVISIBLE);
						}
						break;
						
				
				}
				
			}
			return v;
		}
	}
}
